package tgc.edu.yzy.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import tgc.edu.yzy.entity.BmsRegister;
import tgc.edu.yzy.entity.BmsRole;
import tgc.edu.yzy.repository.RegisterRepository;
import tgc.edu.yzy.security.User2;


@Service
public class CustomUserService implements UserDetailsService{

	@Autowired
	private RegisterRepository userDAO;
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		BmsRegister user = userDAO.findByUsername(username);
		if(user==null) {
			throw new UsernameNotFoundException(username);
		}
		List<BmsRole> roles = user.getBmsRole();
		List<GrantedAuthority> authorities=new ArrayList<>();
		for (BmsRole role : roles) {
			authorities.add(new SimpleGrantedAuthority(role.getCode()));
		}
        return new User2(user.getUsername(), user.getPassword(), user.getId(), user.getName(), authorities);
	}

}
